package com.example.pclimb.ui.requests;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityRequestDetailBinding;
import com.example.pclimb.model.ClimbRequest;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.payment.PaymentActivity;
import com.example.pclimb.ui.review.CreateReviewActivity;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.ClimbRequestViewModel;
import com.example.pclimb.viewmodel.UserViewModel;

import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * 陪爬申请详情页面
 */
public class RequestDetailActivity extends AppCompatActivity {

    private static final String TAG = "RequestDetailActivity";
    private ActivityRequestDetailBinding binding;
    private ClimbRequestViewModel requestViewModel;
    private UserViewModel userViewModel;
    private ClimbRequest currentRequest;
    private User currentUser;
    private User requestUser;
    private User guideUser;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private long requestId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRequestDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 初始化ViewModel
        requestViewModel = new ViewModelProvider(this).get(ClimbRequestViewModel.class);
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 获取请求ID
        if (getIntent().hasExtra("request_id")) {
            requestId = getIntent().getLongExtra("request_id", -1L);
            Log.d(TAG, "收到的请求ID: " + requestId);
            if (requestId == -1L) {
                Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置按钮点击事件
        binding.btnPay.setOnClickListener(v -> navigateToPayment());
        
        // 接单和拒绝按钮点击事件
        binding.btnAcceptRequest.setOnClickListener(v -> acceptRequest());
        binding.btnRejectRequest.setOnClickListener(v -> rejectRequest());

        // 加载请求详情
        loadRequestDetails();
    }

    private void loadRequestDetails() {
        try {
            // 显示加载进度条
            binding.progressBar.setVisibility(View.VISIBLE);
            Log.d(TAG, "开始加载请求详情，ID: " + requestId);

            // 先获取当前用户
            int userId = SharedPreferencesUtil.getUserId(this);
            Log.d(TAG, "当前用户ID从SharedPreferences获取: " + userId);
            
            if (userId > 0) {
                userViewModel.getUserById(userId).observe(this, user -> {
                    if (user != null) {
                        currentUser = user;
                        Log.d(TAG, "成功加载当前用户: " + user.getId() + ", 用户类型: " + user.getUserType());
                        
                        // 在确保加载到当前用户后，再加载请求详情
                        loadRequestData();
                    } else {
                        Log.e(TAG, "当前用户信息为空");
                        binding.progressBar.setVisibility(View.GONE);
                        Toast.makeText(this, "加载用户信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Log.e(TAG, "用户ID无效: " + userId);
                binding.progressBar.setVisibility(View.GONE);
                Toast.makeText(this, "您需要先登录", Toast.LENGTH_SHORT).show();
                finish();
            }
        } catch (Exception e) {
            Log.e(TAG, "加载请求详情出错: ", e);
            binding.progressBar.setVisibility(View.GONE);
            Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    
    /**
     * 加载请求详情数据
     */
    private void loadRequestData() {
        // 获取请求详情 - 确保使用正确的数据类型
        requestViewModel.getRequestById(requestId).observe(this, request -> {
            binding.progressBar.setVisibility(View.GONE);
            if (request != null) {
                Log.d(TAG, "成功加载请求详情: " + request.getId() + ", 状态: " + request.getStatus());
                currentRequest = request;
                updateUI(request);
                
                // 加载请求用户信息
                if (request.getUserId() > 0) {
                    userViewModel.getUserById(request.getUserId()).observe(this, user -> {
                        if (user != null) {
                            requestUser = user;
                            Log.d(TAG, "成功加载请求用户: " + user.getId());
                        }
                    });
                }
                
                // 如果已匹配，加载导游信息
                if (request.getGuideId() != null && request.getGuideId() > 0) {
                    userViewModel.getUserById(request.getGuideId()).observe(this, user -> {
                        if (user != null) {
                            guideUser = user;
                            Log.d(TAG, "成功加载导游用户: " + user.getId());
                        }
                    });
                }
            } else {
                Log.e(TAG, "请求详情为空");
                Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void updateUI(ClimbRequest request) {
        binding.tvLocation.setText(request.getLocation());
        binding.tvDate.setText(dateFormat.format(request.getClimbDate()));
        binding.tvPeopleCount.setText(String.valueOf(request.getNumberOfPeople()));
        binding.tvBudget.setText(String.valueOf(request.getBudget()) + " 元");
        binding.tvDescription.setText(request.getRequirements());
        
        // 根据请求状态更新UI
        updateStatusUI(request.getStatus());
        
        // 检查用户角色，决定是否显示接单按钮
        checkUserRole();
        
        // 日志输出当前用户的身份信息
        if (currentUser != null) {
            Log.d(TAG, "当前用户ID: " + currentUser.getId() + 
                  ", 是否陪爬人员: " + currentUser.isGuide() + 
                  ", 用户类型: " + currentUser.getUserType());
        }
    }

    private void updateStatusUI(int status) {
        // 根据不同状态显示不同的UI元素
        switch (status) {
            case ClimbRequest.STATUS_PENDING:
                binding.statusPending.setVisibility(View.VISIBLE);
                binding.statusMatched.setVisibility(View.GONE);
                binding.statusCompleted.setVisibility(View.GONE);
                binding.btnPay.setVisibility(View.GONE);
                break;
            case ClimbRequest.STATUS_MATCHED:
                binding.statusPending.setVisibility(View.GONE);
                binding.statusMatched.setVisibility(View.VISIBLE);
                binding.statusCompleted.setVisibility(View.GONE);
                binding.btnPay.setVisibility(View.VISIBLE);
                break;
            case ClimbRequest.STATUS_AWAITING_PAYMENT:
                binding.statusPending.setVisibility(View.GONE);
                binding.statusMatched.setVisibility(View.VISIBLE);
                binding.statusCompleted.setVisibility(View.GONE);
                binding.btnPay.setVisibility(View.VISIBLE);
                break;
            case ClimbRequest.STATUS_COMPLETED:
                binding.statusPending.setVisibility(View.GONE);
                binding.statusMatched.setVisibility(View.GONE);
                binding.statusCompleted.setVisibility(View.VISIBLE);
                binding.btnPay.setVisibility(View.GONE);
                
                // 为已完成状态添加去评价按钮
                if (currentUser != null && currentRequest != null 
                    && currentUser.getId() == currentRequest.getUserId()) {
                    Button btnReview = binding.statusCompleted.findViewById(R.id.btn_review);
                    if (btnReview != null) {
                        btnReview.setVisibility(View.VISIBLE);
                        btnReview.setOnClickListener(v -> goToReview());
                    }
                }
                break;
            case ClimbRequest.STATUS_CANCELLED:
                binding.statusPending.setVisibility(View.GONE);
                binding.statusMatched.setVisibility(View.GONE);
                binding.statusCompleted.setVisibility(View.GONE);
                binding.btnPay.setVisibility(View.GONE);
                break;
        }
    }

    private void navigateToPayment() {
        Intent intent = new Intent(this, PaymentActivity.class);
        intent.putExtra("request_id", requestId);
        startActivity(intent);
    }

    /**
     * 接受申请
     */
    private void acceptRequest() {
        if (currentRequest == null || currentUser == null) {
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle(R.string.accept_request)
                .setMessage("确定接受此陪爬申请吗？")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    // 显示进度条
                    binding.progressBar.setVisibility(View.VISIBLE);
                    
                    // 匹配请求
                    requestViewModel.matchRequest(currentRequest.getId(), currentUser.getId());
                    
                    // 更新当前请求状态
                    currentRequest.setStatus(ClimbRequest.STATUS_MATCHED);
                    currentRequest.setGuideId(currentUser.getId());
                    
                    // 更新UI
                    updateUI(currentRequest);
                    
                    // 隐藏进度条，显示成功提示
                    binding.progressBar.setVisibility(View.GONE);
                    Toast.makeText(RequestDetailActivity.this, R.string.accept_success, Toast.LENGTH_SHORT).show();
                    
                    // 延迟一会儿，回到前一页
                    new Handler().postDelayed(() -> finish(), 1500);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 拒绝申请
     */
    private void rejectRequest() {
        if (currentRequest == null) {
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle(R.string.reject_request)
                .setMessage("确定拒绝此陪爬申请吗？")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    // 显示拒绝成功提示
                    Toast.makeText(RequestDetailActivity.this, R.string.reject_success, Toast.LENGTH_SHORT).show();
                    // 返回上一页
                    finish();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 显示设置价格对话框
     */
    private void showSetPriceDialog() {
        if (currentRequest == null) {
            return;
        }

        // 弹出价格设置对话框，而不是直接在界面上显示输入框
        final android.view.View view = getLayoutInflater().inflate(R.layout.dialog_set_price, null);
        final android.widget.EditText etPrice = view.findViewById(R.id.et_price);
        
        new androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle(R.string.set_price)
            .setView(view)
            .setPositiveButton(R.string.save, (dialog, which) -> {
                // 获取输入的价格
                String priceStr = etPrice.getText().toString().trim();
                if (TextUtils.isEmpty(priceStr)) {
                    Toast.makeText(this, R.string.error_field_required, Toast.LENGTH_SHORT).show();
                    return;
                }
                
                try {
                    double price = Double.parseDouble(priceStr);
                    if (price <= 0) {
                        Toast.makeText(this, "价格必须大于0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    // 显示进度条
                    binding.progressBar.setVisibility(View.VISIBLE);
                    
                    // 设置价格
                    requestViewModel.setPrice(currentRequest.getId(), price);
                    
                    // 隐藏进度条，显示成功提示
                    binding.progressBar.setVisibility(View.GONE);
                    Toast.makeText(RequestDetailActivity.this, "价格设置成功", Toast.LENGTH_SHORT).show();
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "请输入有效的价格", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton(R.string.cancel, null)
            .show();
    }

    /**
     * 跳转到评价页面
     */
    private void goToReview() {
        if (currentRequest == null || currentRequest.getGuideId() == null) {
            return;
        }

        Intent intent = new Intent(this, CreateReviewActivity.class);
        intent.putExtra("request_id", currentRequest.getId());
        intent.putExtra("guide_id", currentRequest.getGuideId());
        startActivity(intent);
    }

    /**
     * 完成请求
     */
    private void completeRequest() {
        if (currentRequest == null) {
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle(R.string.complete_request)
                .setMessage("确定已完成此陪爬申请吗？")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    // 显示进度条
                    binding.progressBar.setVisibility(View.VISIBLE);
                    
                    // 完成请求
                    requestViewModel.completeRequest(currentRequest.getId());
                    
                    // 隐藏进度条，显示成功提示
                    binding.progressBar.setVisibility(View.GONE);
                    Toast.makeText(RequestDetailActivity.this, "陪爬已完成", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 检查用户角色，决定是否显示接单按钮
     */
    private void checkUserRole() {
        Log.d(TAG, "检查用户角色");
        
        if (currentUser != null && currentRequest != null) {
            // 记录数据用于调试
            Log.d(TAG, "当前用户ID: " + currentUser.getId() + 
                  ", 用户类型: " + currentUser.getUserType() + 
                  ", 请求状态: " + currentRequest.getStatus() + 
                  ", 请求用户ID: " + currentRequest.getUserId());
            
            // 如果是陪爬人员，且请求状态为待匹配，显示接单按钮
            if (currentUser.isGuide() && 
                currentRequest.getStatus() == ClimbRequest.STATUS_PENDING) {
                // 确保不是自己的请求（用户不能接自己的单）
                if (currentUser.getId() != currentRequest.getUserId()) {
                    Log.d(TAG, "显示接单按钮");
                    binding.llGuideActions.setVisibility(View.VISIBLE);
                } else {
                    Log.d(TAG, "这是用户自己的请求，不显示接单按钮");
                    binding.llGuideActions.setVisibility(View.GONE);
                }
            } else {
                Log.d(TAG, "不符合显示接单按钮的条件");
                binding.llGuideActions.setVisibility(View.GONE);
            }
        } else {
            Log.d(TAG, "用户或请求信息为空，不显示接单按钮");
            binding.llGuideActions.setVisibility(View.GONE);
        }
    }
} 